package com.dola.web.security;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	BCryptPasswordEncoder encoder;

	private final UserDetailsService userDetailsService;

	public CustomAuthenticationProvider(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
		String username = token.getName();
		UserDetails userDetails = null;
		if (username != null) {
			userDetails = userDetailsService.loadUserByUsername(username);
		}
		if (userDetails == null) {
			throw new BadCredentialsException("用户名密码无效");
		} else if (!userDetails.isEnabled()) {
			throw new BadCredentialsException("用户已被禁用");
		} else if (!userDetails.isAccountNonLocked()) {
			throw new BadCredentialsException("账号已被锁定");
		} else if (!userDetails.isCredentialsNonExpired()) {
			throw new BadCredentialsException("凭证已过期");
		}
		String password = userDetails.getPassword();

		if (!encoder.matches(token.getCredentials().toString(), password)) {
			//throw new BadCredentialsException("用户名或密码错误");
		}
		ArrayList<GrantedAuthority> list = new ArrayList<>();
		token.getAuthorities().forEach((e) -> list.add(e));

		return new UsernamePasswordAuthenticationToken(null, password, userDetails.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.equals(authentication);
	}
	
}
